package com.example.test.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.test.common.P;
import com.example.test.domain.Empoyee;
import com.example.test.domain.User;
import com.example.test.service.Userservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private Userservice userservice;

    @PostMapping("/login")
    public P<User> login(HttpServletRequest request, @RequestBody User user){
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,user.getUsername());
        User user1=userservice.getOne(wrapper);
        if(user1==null){
            return P.error("登陆失败");
        }
        if(user1.getPasswd().equals(user.getPasswd())){
            request.getSession().setAttribute("user",user1.getUserid());
            return P.success(user1);
        }
        return P.error("密码错误");
    }
    @PostMapping("register")
    public P<User> register(@RequestBody User user){
        System.out.println(user);
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,user.getUsername());
        User user1=userservice.getOne(wrapper);//如果存在用户名，注册失败
        if(user1!=null){//用户存在
            return P.error("该用户名称已存在");
        }
        user.setRealname(user.getUsername());//默认昵称=账号名
        //不存在就保存新用户
        userservice.save(user);
        return P.success(user);
    }
    @PostMapping("/logout")
    public P<String> logout(HttpServletRequest request, @RequestBody User user){
        //清除session的id;
        request.getSession().removeAttribute("user");
        return P.success("退出成功");
    }
    @GetMapping("/change")
    public P<User> change(HttpServletRequest request){
        int id= Integer.parseInt(request.getParameter("userid"));
        String name=request.getParameter("realname");
        String psw=request.getParameter("passwd");
        int age= Integer.parseInt(request.getParameter("age"));
        System.out.println(name+psw+age);
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserid,id);
        User one = userservice.getOne(wrapper);
        one.setRealname(name);
        one.setPasswd(psw);
        one.setAge(age);
        userservice.update(one,wrapper);
        System.out.println(one);
        return P.success(one);
    }
}
